package com.learn.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 *
 */
@Slf4j
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /**
     * 读取通道数据
     * @param ctx 上下文
     * @param msg 通道数据
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if (msg instanceof HttpRequest) {
            log.info("msg 类型：{}", msg.getClass());
            log.info("客户端地址：{}", ctx.channel().remoteAddress());
            log.info("pipeline hashcode:{}, channel hashcode={}", ctx.pipeline().hashCode(), ctx.channel().hashCode());
            // 回复消息给浏览器
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello 我是服务器", CharsetUtil.UTF_8);

            HttpRequest request = (HttpRequest) msg;
            if (request.uri().contains("ico")) {
                log.info("----不做返回---");
                return;
            }


            /**
             * 构建返回应用
             */
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);

            log.info("readableBytes={}",byteBuf.readableBytes());
            log.info("capacity={}",byteBuf.capacity());
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=utf-8");
            httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());

            ctx.writeAndFlush(httpResponse);
        }
    }
}
